<?php


namespace app\common\exception;


use think\exception\Handle;
use think\facade\Log;
use Throwable;
use think\Response;

class ApiExceptionHandler extends Handle
{
    public function render($request, Throwable $e): Response
    {
        // 如果是 ApiException 异常，直接返回 JSON 格式的错误信息
        if (!$e instanceof ApiException) {
            $data = [
                'time' => date('Y-m-d H:i:s'),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'message' => $e->getMessage()
            ];
            Log::error(json_encode($data));
        }
        $result = [
            'code' => $e->getCode(),
            'msg' => $e->getMessage(),
            'data' => []
        ];
        return json()->data($result);
    }
}